import 'dart:async';
import 'package:flame/components.dart';
import 'package:flame/effects.dart';
import 'package:flame/flame.dart';
import 'package:freedom/page/mahjong/common/common_card.dart';
import 'package:freedom/page/mahjong/mahjong_game.dart';
import '../bloc/user_state.dart';
import '../common/card_build.dart';
import '../common/mahjong_context.dart';
import 'abstract_card_area.dart';
import '../util/user_location.dart';

class TopCardArea extends AbstractHand with HasGameRef<MahjongIndexGame> {
  var mjBgImage = Flame.images.fromCache('mahjong/user/top/usercard.png');
  TopCardArea()
      : super(
            size: MahjongContext().topHandAreaSize,
            position: MahjongContext().topHandAreaPoint);

  @override
  FutureOr<void> onLoad() {}

  @override
  Future<void> reflashUI(UserState userStateParam,
      {List<int>? highlight}) async {
    currentUserState = userStateParam;
    Set<Component> tempSet = Set.from(children);
    for (var item in tempSet) {
      remove(item);
    }

    int? touchCard = currentUserState.touchCard;
    // 不要添加手牌,手牌单独处理
    List<int> userHandCards =
        currentUserState.getUserHandCards(addTouch: false);
    // 判断用户的手牌数量
    int length = userHandCards.isNotEmpty
        ? userHandCards.length
        : currentUserState.handCardCount;
    // 是否添加手牌 三种情况
    if (!currentUserState.win) {
      if (currentUserState.touchCard != null) {
        addTouchCard(currentUserState.touchCard);
      } else if (userHandCards.isNotEmpty && userHandCards.length % 3 == 2) {
        touchCard = userHandCards[length];
        length = length - 1;
        addTouchCard(touchCard);
      } else if (length % 3 == 2) {
        addTouchCard(null);
      }
    } else {
      addWinCard(currentUserState.winCard!);
    }

    double lastX = size.y * MahjongContext().topCardWHRatio * 1.5;

    for (int i = length, j = 0; j < i; j++) {
      PositionComponent cardComponent;
      if (userHandCards.isNotEmpty) {
        cardComponent = CardBuildUtil.topExport(
            Vector2(lastX, 0), userHandCards[j],
            pointTo: null,
            size: MahjongContext().topTBCardSize,
            handCard: true);
      } else {
        cardComponent = SpriteComponent(
            sprite: Sprite(mjBgImage),
            size: Vector2(size.y * MahjongContext().topCardWHRatio, size.y),
            position: Vector2(lastX, 0));
      }
      add(cardComponent);
      lastX += size.y * MahjongContext().topCardWHRatio;
    }
    lastX -= size.y * MahjongContext().topCardWHRatio * 0.5;
    currentUserState.openDeal?.forEach((pItem) {
      // 获取是处理的谁的牌
      Direction? pointTo;
      if (pItem.targetUserSeq != null) {
        pointTo = LocationUtil.buildLocationUtil(MahjongContext.userCount,
            currentUserState.seq, pItem.targetUserSeq!,
            location: Direction.TOP);
      }
      var index = 0;
      pItem.cardList?.forEach((crt) {
        index++;
        lastX += MahjongContext().topTBCardSize.x;
        var positionY = 0.0;
        var showPointTo =
            (index == 3 && pItem.cardList!.length == 4) || index == 2;
        Component? cardInfo;
        if (index == 3 && pItem.cardList!.length == 4) {
          lastX -= MahjongContext().topTBCardSize.x;
          positionY -= MahjongContext().topTBCardSize.y *
              (1 - MahjongContext().exportDiagonalRatio);
          cardInfo = CardBuildUtil.topExport(Vector2(lastX, positionY), crt,
              pointTo: showPointTo ? pointTo : null,
              size: MahjongContext().topTBCardSize);
        } else if (pItem.type == 2) {
          cardInfo = CardBuildUtil.btDarkExport(Vector2(lastX, positionY),
              size: MahjongContext().topTBCardSize);
        } else {
          cardInfo = CardBuildUtil.topExport(Vector2(lastX, positionY), crt,
              pointTo: showPointTo ? pointTo : null,
              size: MahjongContext().topTBCardSize);
        }
        add(cardInfo);
      });
      lastX += MahjongContext().exportCardSize.x / 2;
    });
  }

  @override
  Direction userDirection() {
    return Direction.TOP;
  }

  @override
  Vector2 getHandFirstCardPoint() {
    return Vector2(0, 0);
  }

  @override
  void addWinCard(int card) {
    add(CardBuildUtil.topExport(Vector2(0, 0), card,
        pointTo: null, size: MahjongContext().topTBCardSize));
  }

  /// 新增出牌
  @override
  Component? addTouchCard(int? card) {
    if (TOUCH_CARD != null) {
      TOUCH_CARD!.removeFromParent();
    }
    TOUCH_CARD = card == null
        ? SpriteComponent(
            sprite: Sprite(mjBgImage),
            size: Vector2(size.y * MahjongContext().topCardWHRatio, size.y),
            position: Vector2(0, 0))
        : CardBuildUtil.topExport(Vector2(0, 0), card,
            pointTo: null,
            size: MahjongContext().topTBCardSize,
            handCard: true);
    add(TOUCH_CARD!);
    return TOUCH_CARD;
  }

  @override
  void exportCard(int? card, {ExportCallBack? callBack}) {
    var topExport = gameRef.topExportArea!;
    // 如果能看到手牌 那就直接明牌
    if (currentUserState.getUserHandCards().isNotEmpty && children.isNotEmpty) {
      TOUCH_CARD = children.lastWhere((element) =>
          element is CommonCard &&
          element.handCard &&
          element.cardCode == card) as CommonCard;
    } else {
      // 这里原则上要开放,开发阶段屏蔽调 为了方便动画展示
      TOUCH_CARD ??= addTouchCard(card);
    }
    Vector2 touchCardPoint = (TOUCH_CARD as PositionComponent).position;
    Vector2 pointByScc = topExport.getLastPointByScc(touchCardPoint);
    Effect effect = MoveByEffect(
      pointByScc,
      EffectController(duration: 0.3),
    );
    TOUCH_CARD!.add(effect);
    effect.onComplete = () {
      TOUCH_CARD?.removeFromParent();
      TOUCH_CARD = null;
      topExport.defaultExportCard(card!);
      reflashUI(currentUserState);
      if (callBack != null) {
        callBack(topExport.eportAllCard);
      }
    };
  }

  @override
  void removeCard(int exportCard) {
    if (TOUCH_CARD != null) {
      TOUCH_CARD!.removeFromParent();
    }
  }
}
